// pages/detail-search/index.js
import { getHotKeywords, getSuggestData, getResultData } from '../../service/search_api'
import debounce from '../../utils/debounce'
import textToNodes from '../../utils/text2nodes'
const debounceSearchChange =  debounce(getSuggestData, 400, true)
Page({

  /**
   * 页面的初始数据
   */
  data: {
    searchvalue: null,
    hotKeywords: [],
    suggestList: [],
    resultList: [],
    suggestKeywordNodes: []
  },

  // 事件处理
  handleSearchChange: async function(event) {
    const value = event.detail
    if (!value) {
      this.setData({ suggestList: [], suggestKeywordNodes: [], searchvalue: null, resultList: [] })
      debounceSearchChange.cancel()
      return
    }
    this.setData({ searchvalue: value })
    // 防抖获取建议列表
    const res = await debounceSearchChange(value, 'mobile')
    this.setData({ suggestList: res.result.allMatch })

    // 将keyword转成nodes节点
    const suggestKeywordNodes = textToNodes(this.data.suggestList, value)
    this.setData({ suggestKeywordNodes })
  },
  handleSearchAction: function(event) {
    const value = this.data.searchvalue
    getResultData(value).then(res => {
      this.setData({ resultList: res.result.songs })
    })
  },
  handleItemClick: function(event) {
    const keyword = event.currentTarget.dataset.keyword
    this.setData({ searchvalue: keyword })
    this.handleSearchAction()
  },

  // 获取数据
  getPageData: function() {
    getHotKeywords().then(res => {
      this.setData({ hotKeywords: res.result.hots })
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getPageData()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})